package com.working.libbase.base

import android.net.http.SslError
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.MenuItem.SHOW_AS_ACTION_ALWAYS
import android.webkit.*
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.working.libbase.R
import com.working.libbase.databinding.ActivityWebviewBinding
import com.working.libbase.model.BackUpModel
import com.working.libbase.model.BackupChangeEvent
import com.working.libbase.route.RoutePath
import com.working.libbase.storage.Storage
import com.working.libcommon.bus.LiveDataBus
import com.working.libcommon.exts.bitmapSnapshot
import com.working.libcommon.exts.toast


@Route(path = RoutePath.BASE.WEB_VIEW)
class WebViewActivity : BaseActivity() {

    companion object {
        private const val URL = "url"
        private const val TITLE = "title"
        private const val ANCHOR = "anchor"

        fun start(title: String, url: String, anchor: Int = 0) {
            ARouter.getInstance().build(RoutePath.BASE.WEB_VIEW)
                .withString(URL, url)
                .withString(TITLE, title)
                .withInt(ANCHOR, anchor)
                .navigation()
        }
    }

    private val mBinding by binding<ActivityWebviewBinding>(R.layout.activity_webview)

    @Autowired(name = URL)
    @JvmField
    var mUrl: String? = null

    @Autowired(name = TITLE)
    @JvmField
    var mTitle: String? = null

    @Autowired(name = ANCHOR)
    @JvmField
    var mAnchor: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        title = mTitle
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_arrow_back)
        mBinding.apply {
            lifecycleOwner = this@WebViewActivity
            initWebView(webView)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menu?.add(0, R.id.action_backup, 0, "保存书签")
            ?.setIcon(R.drawable.ic_backup)
            ?.setShowAsAction(SHOW_AS_ACTION_ALWAYS)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_backup) {
            backUp()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private fun backUp() {
        val mBackupList = Storage.backUpList
        val backup = BackUpModel(
            title = this@WebViewActivity.title,
            url = mUrl,
            thumbnail = mBinding.webView.bitmapSnapshot(),
            anchor = mBinding.webView.scrollY
        )
        mBackupList?.add(0, backup)
        Storage.backUpList = mBackupList
        LiveDataBus.send(BackupChangeEvent(backup, -1))
        toast("保存书签成功")
        finish()
    }

    private fun initWebView(webView: WebView) {
        with(webView) {
            settings.apply {
                javaScriptEnabled = true
                useWideViewPort = false //将图片调整到适合webview的大小
                loadWithOverviewMode = false // 缩放至屏幕的大小
                setSupportZoom(true) //支持放大缩小
                builtInZoomControls = true //显示缩放按钮
                blockNetworkImage = true // 把图片加载放在最后来加载渲染
                allowFileAccess = true // 允许访问文件
                saveFormData = true
                setGeolocationEnabled(true)
                domStorageEnabled = true
                javaScriptCanOpenWindowsAutomatically = true /// 支持通过JS打开新窗口

                defaultTextEncodingName = "utf-8"

                //不加这个图片显示不出来
                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                blockNetworkImage = false
            }
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        view.loadUrl(url)
                    }
                    return true
                }

                override fun onScaleChanged(view: WebView?, oldScale: Float, newScale: Float) {
                    super.onScaleChanged(view, oldScale, newScale)
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    view?.scrollTo(0, mAnchor)//webview加载完成后直接定位到上次访问的位置
                }

                override fun onReceivedSslError(
                    view: WebView?,
                    handler: SslErrorHandler?,
                    error: SslError?
                ) {
                    handler?.proceed()
                }
            }
            webChromeClient = object : WebChromeClient() {
                override fun onReceivedTitle(view: WebView, title: String) {
                    super.onReceivedTitle(view, title)
                    this@WebViewActivity.title = title
                }
            }
            loadUrl(mUrl)
        }
    }
}


